/*
 * @Description: 国际化设置工具类
 * @Author: wangfuwei
 * @Date: 2020-12-14 23:11:02
 * @LastEditors: wangfuwei
 * @LastEditTime: 2021-04-23 21:36:11
 * @FilePath: /horizon-frontend/src/locales/util.js
 */

import Vue from "vue";
import { ACCEPT_LANGUAGE, DEFAULT_LANGUAGE } from "@/core/const";

//支持的国际化语言
export const lang = ["zh-CN", "en-US"];

/**
 * 动态设置国际化资源文件
 */
export function dynamicI18n(data) {
  let messages = {};
  lang.forEach(key => (messages[key] = {}));

  let fn = function(item) {
    for (let param in item) {
      if (param === "i18n" && item.fdId) {
        let i18n = item.i18n;
        if (i18n && item.fdId) {
          for (let key in i18n) {
            lang.forEach(l => {
              if (i18n[key][l]) {
                let lang = messages[l];
                lang[item.fdId + "." + key] = i18n[key][l];
              }
            });
          }
        }
      } else if (Array.isArray(item[param])) {
        item[param].forEach(it => fn(it));
      } else if (Object.prototype.toString.call(item[param]) === "[object Object]") {
        fn(item[param]);
      }
    }
  };

  fn(data);

  lang.forEach(key => {
    window.vm.$i18n.setLocaleMessage(key, Object.assign(window.vm.$i18n.getLocaleMessage(key), messages[key]));
  });

  console.log(window.vm.$i18n.getLocaleMessage(DEFAULT_LANGUAGE));
}

/**
 * 获取国际化语言
 */
export function getLanguage() {
  return (window.vm && window.vm.$store.state.app.language) || Vue.ls.get(ACCEPT_LANGUAGE) || navigator.language || DEFAULT_LANGUAGE;
}
